package com.yloveg.controller;

import com.yloveg.base.BaseController;
import com.yloveg.base.Md5Util;
import com.yloveg.base.MyException;
import com.yloveg.common.IpUtil;
import com.yloveg.common.ValidateCode;
import com.yloveg.entity.LoginLog;
import com.yloveg.entity.SUserRole;
import com.yloveg.entity.ShopInfo;
import com.yloveg.entity.Suser;
import com.yloveg.entity.Suser;
import com.yloveg.service.LoginLogService;
import com.yloveg.service.MailUtil;
import com.yloveg.service.SUserRoleService;
import com.yloveg.service.ShopInfoService;
import com.yloveg.service.UserService;

import freemarker.template.TemplateException;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/user")
public class LoginController extends BaseController {
    private final Logger logger = Logger.getLogger(this.getClass());
    
    @Value("#{system.default_role}")
	private String default_role;
    
    @Autowired
    private UserService UserService;
    
    @Autowired
    private LoginLogService loginLogService;
    
    @Autowired
    private MailUtil mailUtil;
    
    @Autowired
    private ShopInfoService shopInfoService;
    
    @RequestMapping("/login")
    public String login(){
        return "user/login";
    }
    @RequestMapping("/register")
    public String register(){
        return "user/register";
    }
    
    @Autowired
    private SUserRoleService sUserRoleService;

    @RequestMapping("/doLogin")
    @ResponseBody
    public Map<String, Object> doLogin(String code,Suser user, String remPwd,HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashedMap<String, Object>();
        
        logger.info("登录:" + user.getUsername() + ":" + user.getPassword());
        HttpSession session = request.getSession();
		String sessionCode = (String) session.getAttribute("code");
		if (!StringUtils.equalsIgnoreCase(code, sessionCode)) {  //忽略验证码大小写
			map.put("code", "2");
			map.put("msg", "验证码错误");
		}else{
			Suser admin = UserService.findUserByNameAndPassword(user.getUsername());
	        if(null != admin){
	        	if(admin.getState()==0){
	        		map.put("code", "2");
	            	map.put("msg", "账号被冻结，请联系管理员");
	        	}
	        }
	        if ((null != admin) && admin.getPassword().equals(Md5Util.encode(user.getPassword()))&&admin.getState()!=0) {
	            setSessionUser(admin);
	            setCookieUser(user.getUsername(), user.getPassword(), remPwd,
	                response);
	            map.put("code", "1");
	            map.put("msg", "登录成功");
	            //店铺信息
	        	ShopInfo info = new ShopInfo();
	        	setSessionShop(info);
	        	info.setUserId(getSessionUser().getId());
	        	info = shopInfoService.queryOneShopInfo(info);
	        	if(info!=null){
	        		setSessionShop(info);	
	        	}
	            LoginLog log = new LoginLog();
	            log.setContent("登录系统");
	            log.setUserName(user.getUsername());
	            log.setUserIp(IpUtil.getLocalIp(request));
	            log.setState(1);
	            log.setCreateDate(new Date());
	            loginLogService.insertUserLog(log);
	        } else{
	            map.put("code", "0");
	            map.put("msg", "账号或密码错误");
	        }			
		}
        return map;
    }

    @RequestMapping("/doRegister")
    @ResponseBody
    public Map<String, Object> doRegister(Suser user, String code,HttpServletRequest request, HttpServletResponse response)throws MyException, IOException, TemplateException {
        Map<String, Object> map = new HashedMap<String, Object>();
        HttpSession session = request.getSession();
		String sessionCode = (String) session.getAttribute("code");
		logger.info("注册:" + user.getUsername() + ":" + user.getPassword()+",code:"+code+",sessionCode="+sessionCode);
		if (!StringUtils.equalsIgnoreCase(code, sessionCode)) {  //忽略验证码大小写
			map.put("code", "2");
			map.put("msg", "验证码错误");
		}else {
			Suser admin = UserService.findUserByNameAndPassword(user.getUsername());
			if(admin!=null) {
				map.put("code", "0");
				map.put("msg", "该用户已经存在！");	
			}else {
				user.setPassword(Md5Util.encode(user.getPassword()));
				int id = UserService.registerUser(user);
				if(id>0) {
					//自动加入默认角色
					Suser newUser = UserService.findUserByNameAndPassword(user.getUsername());
					SUserRole sUserRole = new SUserRole();
					sUserRole.setRoleId(Long.valueOf(default_role));
					sUserRole.setUserId(newUser.getId());
					sUserRoleService.insertSRole(sUserRole);
					//发送邮件
		            Map<String, Object> templateMap = new HashMap<String, Object>();
		            templateMap.put("username", user.getUsername());
		            templateMap.put("adminemail","582182099@qq.com");
		            templateMap.put("time", new Date());
		            mailUtil.sendTemplateMail(templateMap,"注册成功", "registerSuccess.ftl", user.getUsername());
					map.put("code", "1");
					map.put("msg", "注册成功");
				}else {
					map.put("code", "0");
					map.put("msg", "注册错误请联系管理员！");				
				}				
			}
		}
        return map;
    }
    
    
    
	/**
	 * 响应验证码页面
	 * @return
	 */
	@RequestMapping(value="/validateCode")
	public String validateCode(HttpServletRequest request,HttpServletResponse response) throws Exception{
		// 设置响应的类型格式为图片格式
		response.setContentType("image/jpeg");
		//禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
 
		HttpSession session = request.getSession();
 
		ValidateCode vCode = new ValidateCode(120,40,4,100);
		session.setAttribute("code", vCode.getCode());
		vCode.write(response.getOutputStream());
		return null;
	}
    public void setCookieUser(String userName, String password,
        String remberPwd, HttpServletResponse response) {
        /* 将用户名密码保存在cookie中 */
        if ("true".equals(remberPwd)) {
            Cookie cookieUser = new Cookie("cookie_user",
                    userName + "-" + password);
            /* 设定有效时间 以秒(s)为单位 */
            cookieUser.setMaxAge(7 * 24 * 60 * 60);
            /* 设置Cookie路径和域名 */
            cookieUser.setPath("/");
            response.addCookie(cookieUser);
        } else {
            Cookie cookieUser = new Cookie("cookie_user", null);
            /* 设定有效时间 以秒(s)为单位 */
            cookieUser.setMaxAge(0);
            /* 设置Cookie路径和域名 */
            cookieUser.setPath("/");
            response.addCookie(cookieUser);
        }
    }

    public static void main(String[] args) {
        System.out.println(Md5Util.encode("123456"));
        System.out.println("true".equals(null));
    }
    
    @RequestMapping("/signOut")
    public String SignOut(HttpServletRequest request, HttpServletResponse response){
    	System.out.println("用户退出了");
    	Suser user = this.getSessionUser();
    	if(user!=null){
            LoginLog log = new LoginLog();
            log.setContent("退出系统");
            log.setUserName(user.getUsername());
            log.setUserIp(IpUtil.getLocalIp(request));
            log.setState(1);
            log.setCreateDate(new Date());
            loginLogService.insertUserLog(log);
            request.getSession().removeAttribute(BaseController.SESSION_USER);    		
    	}
    	return "user/login";
    }
    
    /**
	 * @todo 用户登录
	 * @since 获取当前用户，
	 * 判断用户是否已经认证登录，
	 * 用账号密码创建UsernamePasswordToken，
	 * 调用subject的login方法
	 * @param
	 * @return
	 */
	@RequestMapping(value = "logon")
	public String logon(Suser user){
		//创建Subject实例对象
		Subject currentUser = SecurityUtils.getSubject();
		//判断当前用户是否已登录
		if(currentUser.isAuthenticated() == false){
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
			try {
				currentUser.login(token);
			} catch (AuthenticationException e) {
				e.getMessage();
				e.printStackTrace();
				System.out.println("登录失败");
				return "logon";
			}
		}
		return "index";
	}
}
